using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Outpatient.Doman.Hospitalization;
using Outpatient.ErrorCode;
using Outpatient.Infrastructure;
using OutpatientApi.DTO;
using OutpatientApi.Methodimplementation.IServices;

namespace OutpatientApi.Controllers
{
    /// <summary>
    /// 住院管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class InpatientManagementController : ControllerBase
    {
        private readonly IInpatientManagement _inpatientManagement;
        private readonly EFDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="inpatientManagement">住院管理服务</param>
        /// <param name="context">数据库上下文</param>
        public InpatientManagementController(IInpatientManagement inpatientManagement, EFDbContext context)
        {
            _inpatientManagement = inpatientManagement;
            _context = context;
        }

        /// <summary>
        /// 测试数据库连接和表结构
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpGet]
        public async Task<IActionResult> TestDatabaseConnection()
        {
            try
            {
                var result = new
                {
                    DatabaseConnected = await _context.Database.CanConnectAsync(),
                    RoomTableExists = await _context.Rooms.AnyAsync(),
                    RoomTypeTableExists = await _context.RoomTypes.AnyAsync(),
                    DepartmentTableExists = await _context.DepartmentInfos.AnyAsync(),
                    RoomCount = await _context.Rooms.CountAsync(),
                    RoomTypeCount = await _context.RoomTypes.CountAsync(),
                    DepartmentCount = await _context.DepartmentInfos.CountAsync()
                };

                return Ok(new { code = 200, msg = "数据库连接测试成功", data = result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = $"数据库连接测试失败: {ex.Message}", data = ex.ToString() });
            }
        }

        /// <summary>
        /// 批量添加病房
        /// </summary>
        /// <param name="batchAddDto">批量添加病房参数</param>
        /// <returns>批量添加结果</returns>
        [HttpPost]
        public async Task<IActionResult> BatchAddRooms([FromBody] BatchAddRoomDto batchAddDto)
        {
            try
            {
                var result = await _inpatientManagement.BatchAddRoomsAsync(batchAddDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { msg = "服务器内部错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 添加单个病房
        /// </summary>
        /// <param name="addDto">添加病房参数</param>
        /// <returns>添加结果</returns>
        [HttpPost]
        public async Task<IActionResult> AddRoom([FromBody] AddRoomDto addDto)
        {
            try
            {
                var result = await _inpatientManagement.AddRoomAsync(addDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { msg = "服务器内部错误", error = ex.Message });
            }
        }


        /// <summary>
        /// 查找病房类型信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<RoomType>>> GetRoomType()
        {
            try
            {
                return await _inpatientManagement.GetRoomType();
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 查找病床号类型信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<HospitalBed>>> GetHospitalBed()
        {
            try
            {
                return await _inpatientManagement.GetHospitalBed();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查找房间号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<RoomDataDto>>> SearchRoomData()
        {
            try
            {
                return await _inpatientManagement.SearchRoomData();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加患者住院登记
        /// </summary>
        /// <param name="addDto">添加患者住院登记参数</param>
        /// <returns>添加结果</returns>
        [HttpPost]
        public async Task<IActionResult> AddPatientAdmission([FromBody] AddPatientAdmissionDto addDto)
        {
            try
            {
                var result = await _inpatientManagement.AddPatientAdmissionAsync(addDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { msg = "服务器内部错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 查询患者住院登记列表（包含关联表信息）
        /// </summary>
        /// <param name="roomNumber">房间号（可选）</param>
        /// <returns>查询结果</returns>
        [HttpGet]
        public async Task<ApiResult<List<PatientAdmissionDto>>> GetPatientAdmissionList(string? roomNumber = null)
        {
            try
            {
                return await _inpatientManagement.GetPatientAdmissionListAsync(roomNumber);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 查找Room表数据（包含关联表信息）
        /// </summary>
        /// <returns>查询结果</returns>
        [HttpGet]
        public async Task<ApiResult<List<RoomDetailDto>>> GetRoomList()
        {
            try
            {
                return await _inpatientManagement.GetRoomListAsync();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 查找病人查找
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<SearchregistrationDto>>> GetPatientAdmission([FromQuery]GetPatientAdmissionDto dto)
        {
            try
            {
                return await _inpatientManagement.GetPatientAdmission(dto);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 实现付款查操作
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<FeeDTO>>> GetFee([FromQuery] GetFeeDto dto)
        {
            try
            {
                return await _inpatientManagement.GetFee(dto);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查找Medicine表信息
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>药品信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<MedicineDto>>> GetMedicine([FromQuery] GetMedicineDto dto)
        {
            try
            {
                return await _inpatientManagement.GetMedicine(dto);
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 查找出院结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<SearchregistrationresultsDto>>> Search_discharge_results([FromQuery] GetPatientAdmissiondischargeDto dto)
        {
            try
            {
                return await _inpatientManagement.Search_discharge_results(dto);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 提交出院实现
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult> Submit_discharge(Submit_dischargeDto dto)
        {
            try
            {
                return await _inpatientManagement.Submit_discharge(dto);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
} 